import React, { useCallback } from 'react';
import addIcon from '@ide/static/svgs/add-icon.svg';
import deleteIcon from '@ide/static/svgs/delete-icon.svg';
import { Input } from 'tea-component';
// 额外信息列表数据
export interface KeyValueItem {
  key: string
  value: string
}

export const getListInit = () => [{ key: '', value: '' }];

export function KeyValueList({
  value,
  onChange
}: {
  value: Array<KeyValueItem>
  onChange: (item: Array<KeyValueItem>) => void
}) {
  const paramContentChanged = useCallback((paramType: string, index: number, val: string) => {
    const changedParams = value.map((item: any, idx: number) => {
      if (idx === index) {
        item[paramType] = val;
      }
      return item;
    });
    onChange(changedParams);
  }, [onChange]);

  return (
    <div>
      {value.map((item, index) => (
        <div key={index} className="extra-info-list">
          <div className="left">
            <div className="key">
              <div className="extra-info-text">key</div>
              <Input
                className="extra-left-input"
                value={item.key}
                onChange={(val) => paramContentChanged('key', index, val)}
              />
            </div>
            <div className="key tea-mt-4n">
              <div className="extra-info-text">value</div>
              <Input
                className="extra-left-input"
                value={item.value}
                onChange={(val) => paramContentChanged('value', index, val)}
              />
            </div>
          </div>
          {index === 0
            ? (
              <img
                src={addIcon}
                alt=""
                onClick={() => {
                  onChange([
                    ...value,
                    {
                      key: '',
                      value: ''
                    }
                  ]);
                }}
              />
            )
            : (
              <img
                src={deleteIcon}
                alt=""
                onClick={() => {
                  value.splice(index, 1);
                  onChange([...value]);
                }}
              />
            )}
        </div>
      ))}
    </div>
  );
}
